#include "stdint.h"
#include "stddef.h"
#include "stdio.h"
#include "stm32f4xx_ll_gpio.h"
#include "iot_gpio.h"
#include "lowpower.h"
#include "gpio_test.h"
#include "los_task.h"
#include "los_compiler.h"
#include "cmsis_os2.h"
#include "ohos_init.h"
#include "ohos_types.h"

LpcType lpcType = NO_SLEEP;

// 读取key电平
static uint16_t read_key(uint16_t key)
{
    uint16_t val;
#ifdef LOSCFG_STM32F407_ATK_USE_HDF
    GpioRead(key, &val);
#endif
#ifdef LOSCFG_STM32F407_ATK_USE_IOTHARDWARE
    IoTGpioGetInputVal(key, &val);
#endif
    return val;
}

// 中断处理函数
static void hdf_key_handler(uint16_t pin)
{
    printf("enter %d hdf interrupt, pin value is %d\n", pin, read_key(pin));
}

static void iot_key_handler(uint16_t pin, char *arg)
{

}

// 初始化KEY
static void key_init_wakeup()
{
#ifdef LOSCFG_STM32F407_ATK_USE_HDF
    printf("Key init use hdf driver...\n");
    // 设置GPIO为输入
    GpioSetDir(KEY3, GPIO_DIR_IN);
    // 注册中断入口
    GpioSetIrq(KEY3, OSAL_IRQF_TRIGGER_RISING, hdf_key_handler, NULL);
    // 使能中断
    GpioEnableIrq(KEY3);
#endif
#ifdef LOSCFG_STM32F407_ATK_USE_IOTHARDWARE
    printf("Key init use iothardware driver...\n");
    // 初始化GPIO结构
    LL_CONFIG_GPIO(KEY3, LL_GPIO_MODE_INPUT, LL_GPIO_PULL_DOWN, LL_GPIO_SPEED_FREQ_HIGH, LL_GPIO_OUTPUT_PUSHPULL, LL_GPIO_AF_0);
    // 初始化GPIO
    IoTGpioInit(KEY3);
    // 设置GPIO为输入
    IoTGpioSetDir(KEY3, IOT_GPIO_DIR_IN);
    // 注册中断入口
    IoTGpioRegisterIsrFunc(KEY3, IOT_INT_TYPE_EDGE, IOT_GPIO_EDGE_RISE_LEVEL_HIGH, iot_key_handler, NULL);
#endif
}

static void led_init(uint8_t led)
{
#ifdef LOSCFG_STM32F407_ATK_USE_HDF
    printf("Led init use hdf driver...\n");
    // 设置GPIO输出模式
    GpioSetDir(led, GPIO_DIR_OUT);
    // 高电平关灯
    GpioWrite(led, GPIO_VAL_HIGH);
#endif
#ifdef LOSCFG_STM32F407_ATK_USE_IOTHARDWARE
    printf("Led init use iothardware driver...\n");
    // 初始化GPIO结构
    LL_CONFIG_GPIO(led, LL_GPIO_MODE_OUTPUT, LL_GPIO_PULL_NO, LL_GPIO_SPEED_FREQ_HIGH, LL_GPIO_OUTPUT_PUSHPULL, LL_GPIO_AF_0);
    // 初始化GOIO
    IoTGpioInit(led);
    // 设置GPIO输出模式
    IoTGpioSetDir(led, IOT_GPIO_DIR_OUT);
    // 输出高电平关灯
    IoTGpioSetOutputVal(led, IOT_GPIO_VALUE1);
#endif
}

void lpc_entry()
{
    printf("----- lowpower test -----\n");
    // 初始化wakeup中断
    key_init_wakeup();
    // 初始化led2
    led_init(LED2);
    led_on(LED2);
    // 初始化一个PWM，用来控制LED
    IoTPwmInit(8);
    IoTPwmStart(8, 50, 1);
    // 浅睡眠模式下，pwm正常驱动LED1闪烁
    // 深度睡眠模式下，pwm停止工作
    LpcSetType(DEEP_SLEEP);
}

void lpc_task()
{
    UINT32 uwRet = -1;
    UINT32 taskID = 0;
    TSK_INIT_PARAM_S stTask = {0};
    stTask.pfnTaskEntry = (TSK_ENTRY_FUNC)lpc_entry;
    stTask.uwStackSize = 0x1000;
    stTask.pcName = "lpc task";
    stTask.usTaskPrio = 10;
    uwRet = LOS_TaskCreate(&taskID, &stTask);
    if (uwRet != LOS_OK) {
        printf("Task fs create failed\n");
    }
}